package org.wj.db;

import akka.actor.AbstractActor;
import akka.actor.Status;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.pf.ReceiveBuilder;
import org.wj.message.GetRequest;
import org.wj.message.KeyNotFoundException;
import org.wj.message.SetRequest;

import java.util.HashMap;
import java.util.Map;

public class AkkaMemoryDb extends AbstractActor {


    protected final LoggingAdapter log = Logging.getLogger(context().system(), this);

    protected final Map<String, Object> map = new HashMap<>();

    @Override
    public Receive createReceive() {
        return ReceiveBuilder.create().match(SetRequest.class, message -> {
            log.info("Received Set request:{}", message);
            map.put(message.getKey(), message.getValue());
            sender().tell(new Status.Success(message.getKey()), self());
        }).match(GetRequest.class, message->{
            log.info("Received Get request:{}", message);
            String key = message.getKey();
            Object value = map.get(key);
            Object response = value != null ? value : new Status.Failure(new KeyNotFoundException(key));
            sender().tell(response, self());
        }).matchAny(o ->{
            sender().tell(new Status.Failure(new ClassNotFoundException()), self());
        }).build();
    }

    public void test() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("123");
            }
        }).start();
    }
}
